package vn.personal.anhht.bloback12.activity;


import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.SMSLogAdapter;
import vn.personal.anhht.bloback12.bean.SMSLogObject;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseSMSAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import vn.personal.anhht.bloback12.widget.ActionBar;
import vn.personal.anhht.bloback12.widget.ActionBar.Action;
import vn.personal.anhht.bloback12.widget.ActionBar.IntentAction;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;


public class LogSMSActivity extends Activity {

    private CallBlockDatabaseSMSAdapter databaseSMSAdapter;
    ArrayList<SMSLogObject> listSMS = new ArrayList<SMSLogObject>();
    SMSLogAdapter adapter = null;
    ListView lvRecycle;
    private ProgressDialog dialog;
    private Resources rs;
    @Override
    
    public void onCreate(Bundle savedInstanceState) {
        Constants.CHECK_LOG_ACTIVITY = false;
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_log_sms);
        rs = getResources();
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle("Block Sms");
        final Action helpAction = new IntentAction(this, createShareIntent(),
                R.drawable.ic_action_help);
        actionBar.addAction(helpAction);
        final Action otherAction = new IntentAction(this, new Intent(this,
                SettingActivity.class), R.drawable.ic_action_settings);
        actionBar.addAction(otherAction);
        actionBar.setHomeAction(new IntentAction(this, HomeActivity.createIntent(this), R.drawable.ic_action_home_default));
        initRecycle();
        new GetSMSThread().execute();
    }
    
    private Intent createShareIntent() {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Shared from the ActionBar widget.");
        return Intent.createChooser(intent, "Share");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mn_filter, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        
        switch(item.getItemId()){
        case R.id.item_filter_back:
            back(RESULT_OK);
            break;
        case R.id.item_filter_clear:{
            final AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle(rs.getString(R.string.bl_alert_title));
            alert.setMessage(rs.getString(R.string.history_alert_msg));
            alert.setPositiveButton(rs.getString(R.string.yes) , new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    new DeleteSMSThread().execute();
                }
            });
            alert.setNegativeButton(rs.getString(R.string.no),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    });
            alert.show();
            break;
        }
        default: return super.onOptionsItemSelected(item);
            
        }
        return true;
    }
    
    private void initRecycle() {
        databaseSMSAdapter = new CallBlockDatabaseSMSAdapter(this);
        lvRecycle = (ListView) findViewById(R.id.lvsmslog);     
        lvRecycle.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                displayDialog(position);
            }
            
        });
        
        
        dialog = new ProgressDialog(LogSMSActivity.this);
        
        adapter = new SMSLogAdapter(getApplicationContext(),
                android.R.layout.simple_list_item_1, listSMS);
    }
    
    public void displayDialog(final int position){
        final SMSLogObject sms = listSMS.get(position);
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(rs.getString(R.string.history_alert_title));
        alert.setMessage(rs.getString(R.string.history_alert_msg_1)+ "\n " + "From: " + sms.getPhone()+"\n "+ "When: " + sms.getTime()+ "\n-------------------------------\n" + sms.getMessage());
        alert.setPositiveButton(rs.getString(R.string.remove), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                databaseSMSAdapter.open();
                databaseSMSAdapter.deleteSms(Integer.parseInt(sms.getId()));
                databaseSMSAdapter.close();
                Toast.makeText(getApplicationContext(), rs.getString(R.string.delete),
                        Toast.LENGTH_LONG).show();
                refresh();
            }
        });
        alert.setNegativeButton(rs.getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });
        alert.show();
    }
    
    private void refresh() {
        
        listSMS.clear();
        new GetSMSThread().execute();
    }
    
    public void back(int resultCode) {

        Intent replyIntent = new Intent();
        setResult(resultCode, replyIntent);
        finish();
    }
    
    private class GetSMSThread extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            
            loadSMSToList();
            return null;
        }
        
        @Override
        protected void onPreExecute() {
            
            //super.onPreExecute();
            dialog.setMessage(rs.getString(R.string.bl_dialog_load));
            dialog.show();
        }

        @Override
        protected void onPostExecute(Void result) {
            
            if(dialog.isShowing()){
                dialog.dismiss();
            }
            lvRecycle.setAdapter(adapter);
        }
        
        private ArrayList<SMSLogObject> loadSMSToList(){
            //ArrayList<SMSLogObject> list = new ArrayList<SMSLogObject>();
            databaseSMSAdapter.open();
            Cursor cursor = databaseSMSAdapter.selectAllSms();
            if(cursor.moveToFirst()){
                int indexOfPhone = cursor.getColumnIndex(CallBlockDatabaseSMSAdapter.KEY_FROM);
                int indexOfTime = cursor.getColumnIndex(CallBlockDatabaseSMSAdapter.KEY_TIME);
                int indexOfContent = cursor.getColumnIndex(CallBlockDatabaseSMSAdapter.KEY_CONTENT);
                int indexOfId = cursor.getColumnIndex(CallBlockDatabaseSMSAdapter.KEY_ID);
                
                do{
                    SMSLogObject sms = new SMSLogObject();
                    sms.setId(cursor.getString(indexOfId));
                    sms.setPhone(cursor.getString(indexOfPhone));
                    sms.setTime(cursor.getString(indexOfTime));
                    sms.setMessage(cursor.getString(indexOfContent));
                    listSMS.add(sms);
                }while(cursor.moveToNext());
            }
            cursor.close();
            databaseSMSAdapter.close();
            //return list;
            return null;
        }
    }
    
    private class DeleteSMSThread extends AsyncTask<Void, Void, Void>{

        
        @Override
        protected Void doInBackground(Void... arg0) {
            
            databaseSMSAdapter.open();
            databaseSMSAdapter.deleteAll();
            databaseSMSAdapter.close();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            
            //super.onPostExecute(result);
            if(dialog.isShowing()){
                dialog.dismiss();
            }
            //refresh();
            listSMS.clear();
            lvRecycle.setAdapter(adapter);
            Toast.makeText(getApplicationContext(), "Delete finished", Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPreExecute() {
            
            //super.onPreExecute();
            dialog.setMessage(rs.getString(R.string.bl_dialog_delete));
            dialog.show();
        }
        
    }
    
}
